<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { userApi, baseApi } from '@/api'
import { getPrePage } from '@/utils/common'

const routerParam = ref<any>({})
const addressData = ref<any>({})
const defaultAddress = ref(false)
const type = ref()
const isFirstGet = ref(false)
// 是否是供应链
const isGYL = ref()
const originProvinceArr = ref<any>([])
// 地址数组
const addressArr = ref<any>([])
// 选择的父级id,0为省
const selectParentid = ref(0)
const showAddress = ref(false)
const fieldValue = ref('')
const cascaderValue = ref('')
const formErrors = reactive<any>({
  name: '',
  phone: '',
  region: '',
  other: ''
})
// 新增：维护选择历史路径（记录每一级的选择）
const selectionHistory = ref<any[]>([])
// 新增：当前层级（1-4分别对应省/市/区/街道）
const currentLevel = ref(1)
// 获取城市数据
const handleGetAddress = async (parentId: number, level: number) => {
  try {
    const { code, data } = await baseApi.getAddressListById({
      noPaging: true,
      parentId
    })

    if (code == 200 && Array.isArray(data)) {
      // 仅在成功且数据为数组时更新地址列表
      const formattedData = data.map((ele: any) => ({
        ...ele,
        text: ele.name,
        value: ele.id,
        deep: level
      }))
      currentLevel.value = level
      addressArr.value = formattedData
      return data // 返回原始数据用于后续处理
    } else {
      console.error('获取地址数据失败，状态码:', code)
      return [] // 失败时返回空数组
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    return [] // 异常时返回空数组
  }
}
const handleOpenAddress = async () => {
  // 重置选择状态，但保留已加载的数据
  if (type.value !== 'edit') {
    // 如果是新增模式且还没加载过省级数据，则加载
    if (addressArr.value.length === 0) {
      handleGetAddress(0, 1)
    }
  }
  // 直接显示弹窗，不处理数据加载
  showAddress.value = true
}
//地址选择变化处理
const handleChangeArea = (e: any) => {
  const { selectedOptions } = e
  const currentSelectObj = selectedOptions[0]

  // 更新历史记录
  if (currentSelectObj.deep <= selectionHistory.value.length) {
    // 如果当前层级小于等于历史长度，截断历史记录
    selectionHistory.value = selectionHistory.value.slice(
      0,
      currentSelectObj.deep - 1
    )
  }
  selectionHistory.value.push({
    id: currentSelectObj.id,
    name: currentSelectObj.name,
    deep: currentSelectObj.deep
  })

  // 更新地址数据
  switch (currentSelectObj.deep) {
    case 1:
      addressData.value.provinceName = currentSelectObj.name
      addressData.value.provinceId = currentSelectObj.id
      addressData.value.cityName = ''
      addressData.value.districtName = ''
      addressData.value.street = ''
      break
    case 2:
      addressData.value.cityName = currentSelectObj.name
      addressData.value.cityId = currentSelectObj.id
      addressData.value.districtName = ''
      addressData.value.street = ''
      break
    case 3:
      addressData.value.districtName = currentSelectObj.name
      addressData.value.districtId = currentSelectObj.id
      addressData.value.street = ''
      break
    case 4:
      addressData.value.street = currentSelectObj.name
      addressData.value.streetId = currentSelectObj.id
      handleCloseArea()
      return
  }

  // 加载下一级数据
  handleGetAddress(currentSelectObj.id, currentSelectObj.deep + 1)
}
// 关闭地址选择弹窗时重置
const handleCloseArea = () => {
  selectParentid.value = 0
  showAddress.value = false
}
// 回退到指定层级
const goToLevel = (level: number) => {
  if (level >= currentLevel.value) return // 不能回退到当前或更低层级
  // 截取历史记录到目标层级
  const newHistory = selectionHistory.value.slice(0, level)
  // 更新历史记录
  selectionHistory.value = newHistory
  // 清空目标层级以下的地址数据
  const levels = [
    { key: 'street', deep: 4 },
    { key: 'district', deep: 3 },
    { key: 'city', deep: 2 },
    { key: 'province', deep: 1 }
  ]

  levels.forEach((item) => {
    if (item.deep > level) {
      addressData.value[`${item.key}Name`] = ''
      addressData.value[`${item.key}Id`] = ''
    }
  })
  // 加载目标层级的数据
  if (newHistory.length === 0) {
    // 回退到省份层级
    handleGetAddress(0, 1)
  } else {
    // 回退到指定层级的下一级数据
    const lastSelection = newHistory[newHistory.length - 1]
    handleGetAddress(lastSelection.id, level + 1)
  }
}

// 清除错误信息
const clearErrors = () => {
  Object.keys(formErrors).forEach((key) => {
    formErrors[key] = ''
  })
}

// 验证表单
const validateForm = () => {
  clearErrors()
  let isValid = true

  // 验证联系人姓名
  if (!addressData.value.name?.trim()) {
    formErrors.name = '联系人姓名不能为空'
    isValid = false
  } else if (addressData.value.name.trim().length < 2) {
    formErrors.name = '联系人姓名长度至少2个字符'
    isValid = false
  }

  // 验证手机号
  if (!addressData.value.phone?.trim()) {
    formErrors.phone = '手机号码不能为空'
    isValid = false
  } else if (!/^1[3-9]\d{9}$/.test(addressData.value.phone)) {
    formErrors.phone = '请输入正确的手机号码格式'
    isValid = false
  }

  if (
    !addressData.value.provinceName ||
    !addressData.value.cityName ||
    !addressData.value.districtName ||
    !addressData.value.street
  ) {
    formErrors.region = '请选择完整的省市区街道地址'
    isValid = false
  }

  // 验证详细地址
  if (!addressData.value.other?.trim()) {
    formErrors.other = '详细地址不能为空'
    isValid = false
  }
  // else if (addressData.value.other.trim().length < 5) {
  //   formErrors.other = '详细地址至少需要5个字符'
  //   isValid = false
  // }

  return isValid
}

// 显示错误提示
const showErrorToast = (message: string) => {
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
}

// 默认地址选择
function switchChange(e: { detail: { value: boolean } }) {
  defaultAddress.value = e.detail.value
}

// 提交
async function confirm() {
  console.log('addressData', addressData.value)

  if (!validateForm()) {
    // 如果有错误，显示第一个错误信息
    const firstError = Object.values(formErrors).find((error) => error)
    if (firstError) {
      showErrorToast(firstError)
    }
    return
  }

  const {
    provinceName,
    cityName,
    districtName,
    street,
    phone,
    name,
    other,
    provinceId,
    cityId,
    districtId,
    streetId
  } = addressData.value

  uni.showLoading({ title: '提交中...', mask: true })

  try {
    const { id, addressId, userId } = routerParam.value
    const executor =
      type.value === 'edit' ? userApi.updateAddressInfo : userApi.addressAdd

    await executor({
      address: {
        provinceName,
        cityName,
        districtName,
        street,
        other,
        provinceId,
        cityId,
        districtId,
        streetId,
        phone,
        name,
        userId,
        id: addressId
      },
      id,
      userId,
      addressId,
      defaultAddress: defaultAddress.value,
      type: isGYL.value == 5 ? isGYL.value : 0
    })

    uni.showToast({
      title: `地址${type.value === 'edit' ? '修改' : '添加'}成功`,
      icon: 'success',
      duration: 2000
    })

    setTimeout(() => {
      try {
        const prePage = getPrePage()
        prePage && prePage.loadData()
      } catch (err) {
        console.log(err)
      }
      uni.$emit('addressEdit')
      uni.navigateBack()
    }, 1000)
  } catch (error) {
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}

// 地图选择地址
function chooseLocation() {
  uni.chooseLocation({
    success: async (data) => {
      const { latitude, longitude } = data
      if (!latitude || !longitude) {
        return
      }
      const res = await baseApi.reverseGeocoding({ latitude, longitude })
      if (res.code !== 200) return
      const {
        provinceName,
        cityName,
        districtName,
        street,
        provinceId,
        cityId,
        districtId
      } = res.data
      console.log('选择地址的返回', res.data)

      addressData.value.provinceName = provinceName
      addressData.value.cityName = cityName
      addressData.value.districtName = districtName
      addressData.value.street = street
      addressData.value.provinceId = provinceId
      addressData.value.cityId = cityId
      addressData.value.districtId = districtId

      // 清除地区错误
      formErrors.region = ''
    },
    fail: (error) => {
      console.log('error', error)
    }
  })
}

// 输入时清除错误信息
const clearError = (field: string) => {
  formErrors[field] = ''
}
// 预加载编辑模式的完整地址数据
const preloadEditAddressData = async () => {
  const { provinceId, cityId, districtId, streetId } = addressData.value
  // 过滤掉无效ID
  const levelIds = [
    { id: provinceId, deep: 1 },
    { id: cityId, deep: 2 },
    { id: districtId, deep: 3 },
    { id: streetId, deep: 4 }
  ].filter((level) => level.id && level.id !== '') // 过滤空值和无效ID
  // 按层级预加载地址数据
  for (const level of levelIds) {
    const parentId = level.deep === 1 ? 0 : levelIds[level.deep - 2]?.id || 0
    // 确保parentId有效
    if (!parentId && level.deep > 1) {
      console.warn(`跳过层级${level.deep}，父级ID无效`)
      break
    }
    const data = await handleGetAddress(parentId, level.deep)
    // 检查数据有效性
    if (!Array.isArray(data) || data.length === 0) {
      console.warn(`层级${level.deep}没有数据，停止加载`)
      break
    }
    const selectedItem = data.find((item: any) => item.id === level.id)
    if (selectedItem) {
      selectionHistory.value.push({
        id: selectedItem.id,
        name: selectedItem.name,
        deep: level.deep
      })
      currentLevel.value = selectedItem.deep
      cascaderValue.value = selectedItem.id
    } else {
      console.warn(`在层级${level.deep}中未找到ID为${level.id}的地址`)
      break
    }
  }
}

onLoad(async (option: any) => {
  console.log('编辑地址option', option)
  type.value = option?.type
  if (type.value == 'edit') {
    routerParam.value = uni.getStorageSync('routerParam')
    addressData.value = { ...routerParam.value.address } // 深拷贝避免引用问题
    defaultAddress.value = routerParam.value.defaultAddress
    // 预加载已选的完整的地址层级
    await preloadEditAddressData()
  } else {
    handleGetAddress(0, 1) // 初始化加载省份数据（第一级）
  }
  isFirstGet.value = true
  isGYL.value = option.isGYL
})
</script>

<template>
  <!-- <hy-nav-bar :title="'地址编辑'"></hy-nav-bar> -->
  <view class="content">
    <!-- 联系人 -->
    <view class="row b-b">
      <view class="tit tit2">联系人</view>
      <view class="input-container">
        <input
          class="input"
          type="text"
          v-model="addressData.name"
          maxlength="20"
          placeholder="收货人姓名"
          placeholder-class="placeholder"
          @input="clearError('name')"
        />
        <text class="error-text" v-if="formErrors.name">{{
          formErrors.name
        }}</text>
      </view>
    </view>

    <!-- 手机号 -->
    <view class="row b-b">
      <view class="tit tit2">手机号</view>
      <view class="input-container">
        <input
          class="input"
          type="number"
          maxlength="11"
          v-model="addressData.phone"
          placeholder="收货人手机号码"
          placeholder-class="placeholder"
          @input="clearError('phone')"
        />
        <text class="error-text" v-if="formErrors.phone">{{
          formErrors.phone
        }}</text>
      </view>
    </view>

    <!-- 选择地区 -->
    <view class="row icon-row b-b">
      <view class="tit tit2">选择地区</view>
      <view class="input-container">
        <view class="input-wrap">
          <view
            class="input"
            @click="handleOpenAddress"
            style="
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding-right: 20rpx;
            "
          >
            <view style="word-wrap: normal; white-space: normal"
              >{{ addressData.provinceName }}{{ addressData.cityName }}
              {{ addressData.districtName }}
              {{ addressData.street }}
            </view>
            <view
              class="place"
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <view style="width: 120rpx"> 点击选择 </view>

              <!-- <view class="place" @click="chooseLocation"
                >定位<u-icon name="map-fill" size="36"></u-icon
              ></view> -->
            </view>
          </view>
        </view>
        <text class="error-text" v-if="formErrors.region">{{
          formErrors.region
        }}</text>
      </view>
    </view>

    <!-- 详细地址 -->
    <view class="row icon-row b-b">
      <view class="tit tit2">详细地址</view>
      <view class="input-container">
        <input
          class="input"
          type="text"
          v-model="addressData.other"
          maxlength="50"
          placeholder="楼号、门牌等"
          placeholder-class="placeholder"
          @input="clearError('other')"
        />
        <text class="error-text" v-if="formErrors.other">{{
          formErrors.other
        }}</text>
      </view>
    </view>

    <!-- 默认地址 -->
    <view class="row default-row">
      <view class="tit">设为默认</view>
      <switch
        :checked="defaultAddress"
        color="#f92c1d"
        @change="switchChange"
      />
    </view>

    <!-- 提交按钮 -->
    <view @tap="confirm" class="add-btn">提交</view>
    <!--地址选择弹窗，增加层级导航 -->
    <van-popup :show="showAddress" round position="bottom">
      <!-- 新增：层级导航栏 -->
      <view class="address-nav">
        <view
          class="nav-item"
          :class="{ active: currentLevel > 1 }"
          @click="goToLevel(0)"
        >
          {{ selectionHistory[0]?.name || '请选择省份' }}
        </view>
        <view class="nav-divider" v-if="currentLevel > 1">/</view>
        <view
          class="nav-item"
          :class="{ active: currentLevel > 2 }"
          @click="goToLevel(1)"
          v-if="currentLevel > 1"
        >
          {{ selectionHistory[1]?.name || '请选择城市' }}
        </view>
        <view class="nav-divider" v-if="currentLevel > 2">/</view>
        <view
          class="nav-item"
          :class="{ active: currentLevel > 3 }"
          @click="goToLevel(2)"
          v-if="currentLevel > 2"
        >
          {{ selectionHistory[2]?.name || '请选择区县' }}
        </view>
        <view class="nav-divider" v-if="currentLevel > 3">/</view>
        <view
          class="nav-item"
          :class="{ active: currentLevel > 4 }"
          @click="goToLevel(3)"
          v-if="currentLevel > 3"
        >
          {{ selectionHistory[3]?.name || '请选择乡镇' }}
        </view>
      </view>
      <van-cascader
        v-model:show="showAddress"
        v-model="cascaderValue"
        :options="addressArr"
        @close="handleCloseArea"
        @change="handleChangeArea"
      />
    </van-popup>
  </view>
</template>

<style lang="scss" scoped>
.content {
  padding-top: 16rpx;
  min-height: 100vh;
  background-color: #f5f5f5;

  .row {
    display: flex;
    align-items: center; // 保持整体垂直居中
    position: relative;
    padding: 0 30rpx;
    min-height: 110rpx;
    background: #fff;
    border-bottom: 1px solid #efefef;

    &.icon-row {
      padding-right: 10rpx;
    }

    .tit {
      flex-shrink: 0;
      width: 152rpx;
      font-size: 30rpx;
      color: $text-color-dark;
      padding: 30rpx 0;
    }
    .tit2::before {
      content: '*';
      color: red;
    }
    .input-container {
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .input-wrap {
      height: 100%;
      flex: 1;
      display: flex;
    }

    .input {
      flex: 1;
      font-size: 30rpx;
      color: $text-color-dark;
      height: 110rpx;
      display: flex;
      align-items: center;
      padding: 0;
    }

    .error-text {
      color: #f92c1d;
      font-size: 24rpx;
      margin-top: 8rpx;
      margin-bottom: 16rpx;
    }

    .place {
      font-size: 30rpx;
      color: #808080;
    }

    .rightImg {
      width: 12rpx;
      height: 21rpx;
      margin-right: 20rpx;
      margin-left: 20rpx;
      margin-top: 45rpx;
    }
  }

  .default-row {
    margin-top: 16rpx;
    align-items: center;

    .tit {
      flex: 1;
      padding: 0;
    }

    switch {
      transform: translateX(16rpx) scale(0.9);
    }
  }

  .add-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 690rpx;
    height: 80rpx;
    margin: 60rpx auto;
    font-size: 30rpx;
    color: #fff;
    background-color: $base-color-mall;
    border-radius: 10rpx;
    box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
  }
}
// 新增：地址选择层级导航样式
.address-nav {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  flex-wrap: nowrap;
  overflow-x: auto;
  white-space: nowrap;

  .nav-item {
    font-size: 28rpx;
    color: #666;
    padding: 0 10rpx;
    cursor: pointer;
    &.active {
      color: #007aff;
      font-weight: 500;
    }
  }

  .nav-divider {
    color: #ccc;
    margin: 0 5rpx;
  }

  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
